package com.wt.struggle.goodbye.db

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.wt.struggle.goodbye.info.ProUserInfo


class DbUtil(context: Context) {

    private var dbHelper: DbHelper? = null

    init {
        dbHelper = DbHelper(context)
    }

    fun getAccountList(): ArrayList<ProUserInfo> {
        val arr = arrayListOf<ProUserInfo>()

        val sql = dbHelper!!.readableDatabase

        val cursor = sql.query(DbHelper.NAME, null, null, null, null, null, null, null)
        while (cursor.moveToNext()) {
            val userInfo = ProUserInfo()
            userInfo.avatarurl = cursor.getString(cursor.getColumnIndex(DbHelper.IMAGE_HEAD))
            userInfo.nickName = cursor.getString(cursor.getColumnIndex(DbHelper.USER_NAME))
            userInfo.account = cursor.getString(cursor.getColumnIndex(DbHelper.ACCOUNT))
            userInfo.pwd = cursor.getString(cursor.getColumnIndex(DbHelper.PWD))
            arr.add(userInfo)
        }
        cursor.close()

        return arr

    }


    fun addAccount(userInfo: ProUserInfo):String {

        val sql = dbHelper!!.readableDatabase

        if (!isExist(sql, userInfo.account)) {
            val contentValues = ContentValues()
            contentValues.put(DbHelper.ACCOUNT, userInfo.account)
            contentValues.put(DbHelper.PWD, userInfo.pwd)
            contentValues.put(DbHelper.IMAGE_HEAD, userInfo.avatarurl)
            contentValues.put(DbHelper.USER_NAME, userInfo.nickName)
            val aa=sql.insert(DbHelper.NAME, null, contentValues)
            return "添加成功"

        }else{
            return "账号已存在"
        }

    }


    fun update(userInfo: ProUserInfo) {

        Log.i("result","-----"+userInfo.nickName+"------"+userInfo.avatarurl)

        val sql = dbHelper!!.readableDatabase
        val contentValues = ContentValues()
        contentValues.put(DbHelper.IMAGE_HEAD, userInfo.avatarurl)
        contentValues.put(DbHelper.USER_NAME, userInfo.nickName)
        sql.update(DbHelper.NAME, contentValues, "${DbHelper.ACCOUNT} = ?", arrayOf(userInfo.account))
    }


    private fun isExist(sql: SQLiteDatabase?, account: String?): Boolean {

        val cursor =
            sql!!.query(DbHelper.NAME, null, "${DbHelper.ACCOUNT} = ?", arrayOf(account), null, null, null, null)
        if (cursor.moveToNext()) {
            cursor.close()
            return true
        }
        cursor.close()
        return false

    }

}